# -*- coding: utf-8 -*-
'''
@author: lowzoom
'''
from __future__ import print_function
import win32_util
import os

# hosts文件路径
HOSTS_PATH = os.path.join(win32_util.get_system32(), 'drivers', 'etc', 'hosts')

# EA的登录服务器
EA_HOST = 'gosredirector.ea.com'

# localhost
LOCAL_IP = '127.0.0.1'

def get_ea_ip(line):
	'''
	判断是否为EA的服务器地址，如果是返回其IP，否则返回None
	@param line: hosts文件中的一行
	'''
	line = line.strip()
	if line.startswith('#'):
		return None

	line = line.replace('#', ' #')
	parts = line.split()

	if len(parts) >= 2 and parts[1] == EA_HOST:
		return parts[0]
	return None

def is_skip_connect():
	'''
	是否跳过与EA服务器的连接
	'''
	with open(HOSTS_PATH, 'r') as hosts_file:
		for line in hosts_file:
			if get_ea_ip(line) == LOCAL_IP:
				return True
	return False

def set_skip_connect(skip):
	'''
	设置是否跳过与EA服务器的连接
	@param skip:
	'''
	new_hosts = []

	with open(HOSTS_PATH, 'r') as hosts_file:
		while True:
			line = hosts_file.readline()
			ea_ip = get_ea_ip(line)

			if line == '' or ea_ip:
				break
			new_hosts.append(line)

		# 读完里面都没EA的地址，但想跳过就直接在最后添加EA地址
		if line == '' and skip:
			new_hosts.append('{br}\n{ip} {ea}\n'.format(
				ip=LOCAL_IP,
				ea=EA_HOST,
				br='' if new_hosts[-1].endswith('\n') and \
								new_hosts[-1] != '\n' else '\n'))
		# 如果已经屏蔽了EA的服务器，但想恢复，就删除此行
		elif ea_ip == LOCAL_IP and not skip:
			pass
		# 其他情况保持原样即可，无需修改文件
		else:
			return

		while line:
			line = hosts_file.readline()
			if line:
				new_hosts.append(line)

	with open(HOSTS_PATH, 'w') as hosts_file:
		hosts_file.write(''.join(new_hosts).strip())

if __name__ == '__main__':
	skiped = is_skip_connect()
	print('skiped: %s' % skiped)
	set_skip_connect(not skiped)
